/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlinkdemo.fragment;

import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.xuexiang.xaop.annotation.MainThread;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xdlink.XDLink;
import com.xuexiang.xdlink.component.buffer.IBuffer;
import com.xuexiang.xdlink.component.channel.IChannel;
import com.xuexiang.xdlink.component.channel.OnChannelListener;
import com.xuexiang.xdlink.exception.BufferException;
import com.xuexiang.xdlink.exception.ChannelException;
import com.xuexiang.xdlink.util.ConvertTools;
import com.xuexiang.xdlinkdemo.R;
import com.xuexiang.xdlinkdemo.util.SettingSpUtils;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageFragment;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author xuexiang
 * @since 2018/9/17 上午1:58
 */
@Page(name = "通信通道演示")
public class ChannelTestFragment extends XPageFragment implements OnChannelListener{

    IChannel mChannel;

    IBuffer mBuffer;

    @BindView(R.id.et_vid)
    EditText etVid;
    @BindView(R.id.et_pid)
    EditText etPid;
    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.tv_content)
    TextView tvContent;

    @Override
    protected void initArgs() {
        super.initArgs();
        mBuffer = XDLink.buffer();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_channel_test;
    }

    @Override
    protected void initViews() {
        etVid.setText(SettingSpUtils.get().getVID());
        etPid.setText(SettingSpUtils.get().getPID());
    }

    @Override
    protected void initListeners() {

    }

    @SingleClick
    @OnClick({R.id.btn_open, R.id.btn_close, R.id.btn_send})
    public void onViewClicked(View view) {
        tvContent.setText("");
        switch (view.getId()) {
            case R.id.btn_open:
                openChannel();
                break;
            case R.id.btn_close:
                closeChannel();
                break;
            case R.id.btn_send:
                sendMessage();
                break;
        }
    }

    private void openChannel() {
        if (mChannel == null) {
            String vid = etVid.getText().toString().trim();
            String pid = etPid.getText().toString().trim();
            if (StringUtils.isEmpty(vid) || StringUtils.isEmpty(pid)) {
                ToastUtils.toast("请输入VID和PID");
                return;
            }

            mChannel = XDLink.usb(getContext())
                    .setVendorId(StringUtils.toInt(vid, -1))
                    .setProductId(StringUtils.toInt(pid, -1))
                    .build();

            mChannel.setOnChannelListener(this);
        }

        mChannel.openChannel();

    }

    /**
     * 关闭通道
     */
    private void closeChannel() {
        if (mChannel != null) {
            mChannel.closeChannel();
        }
    }

    private void sendMessage() {
        if (mChannel == null || !mChannel.isOpen()) {
            ToastUtils.toast("请先打开通道连接!");
            return;
        }

        String message = etInput.getText().toString().trim();
        if (StringUtils.isEmpty(message)) {
            ToastUtils.toast("发送内容不能为空!");
            return;
        }

        try {
            mChannel.write(ConvertTools.hexStringToBytes(message));
        } catch (ChannelException e) {
            e.printStackTrace();
            ToastUtils.toast(e.getMessage());
        }
    }

    @Override
    public void onConnectStatusChanged(IChannel channel) {
        switch(channel.getConnectStatus()) {
            case CONNECT_SUCCESS:
                ToastUtils.toast("连接成功！");
                SettingSpUtils.get().setVID(etVid.getText().toString().trim());
                SettingSpUtils.get().setPID(etPid.getText().toString().trim());
                break;
            case CONNECT_FAILED:
                ToastUtils.toast("连接失败！");
                break;
            case ALREADY_CONNECTED:
                ToastUtils.toast("已连接！");
                break;
            case DISCONNECT_SUCCESS:
                ToastUtils.toast("已断开！");
                break;
            default:
                break;
        }
    }

    @Override
    public void onDataReceived(IChannel channel, byte[] data, int available) {
        if (available > 0) {
            try {
                mBuffer.putData(data, available);
                final byte[] bytes = mBuffer.getData();
                mBuffer.release(bytes.length);

                onUpdateMessage(ConvertTools.bytes2HexString(bytes));
            } catch (BufferException e) {
                e.printStackTrace();
            }
        }
    }

    @MainThread
    public void onUpdateMessage(String message) {
        tvContent.setText(message);
    }

    @Override
    public void onDestroyView() {
        closeChannel();
        super.onDestroyView();
    }


}
